﻿using Seeker.Model.Interface;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;

namespace Seeker.DAL.Admin
{
    public class Login: Interface.ILoginVerify
    {
        /// <summary>
        /// 登陆系统
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public IBaseAUserInfo SignIn(string userName, string password)
        {
            SqlDataReader dr;
            IBaseAUserInfo userInfo = new Seeker.Model.AUsers();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = new SqlConnection(SqlHelper.AdminConnectionStr);
            cmd.CommandText = "SELECT UID, ACCOUNT, [KEY] FROM AUSER WHERE ACCOUNT = @ACCOUNT AND ACCOUNT_PWD = @PASSWORD";

            cmd.Parameters.Add("@ACCOUNT", SqlDbType.VarChar, 30).Value = userName;
            cmd.Parameters.Add("@PASSWORD", SqlDbType.Char, 32).Value = password;
            cmd.Connection.Open();

            dr = cmd.ExecuteReader();

            if (dr.Read())
            {
                userInfo.UID = (int)dr["UID"];
                userInfo.Account = dr["ACCOUNT"].ToString();
                userInfo.Key = dr["KEY"].ToString();

                cmd.Connection.Close();

                return userInfo;
            }
            else
            {
                cmd.Connection.Close();

                return null;
            }
        }

        /// <summary>
        /// 通过uid与key验证用户的有效性
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool LoginVerify(int uid, string key)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = new SqlConnection(SqlHelper.AdminConnectionStr);
            cmd.CommandText = "SELECT UID FROM AUSER WHERE UID = @UID AND [KEY] = @KEY";
            cmd.Parameters.Add("@UID", SqlDbType.Int).Value = uid;
            cmd.Parameters.Add("@KEY", SqlDbType.Char, 32).Value = key;

            SqlDataReader dr = cmd.ExecuteReader();
            bool success = dr.Read();

            cmd.Connection.Close();

            return success;
        }
    }
}
